import { useState } from 'react'
import { Button, Form, Input, message } from 'antd';
import axios from '@/utils/Request';

function Index() {

  const [messageApi, contextHolder] = message.useMessage();

  // 登陆成功
  const onFinish = async (values: any) => {
    await axios.post('/user/login', {
      username: values.username,
      password: values.password,
      captcha: values.Nickname
    }).then((res: any) => {
      // console.log(res)
      if (res.data.code === 1) {
        messageApi.open({
          type: 'success',
          content: res.data.message,
        });
        // 登录成功,存入本地token
        localStorage.setItem('token', res.data.token)
        localStorage.setItem('id', res.data.id)
        setTimeout(() => {
          window.location.href = '/main/fangyuan'
        }, 2000);
      } else {
        messageApi.open({
          type: 'error',
          content: res.data.message,
        });
      }
    }).catch((res: any) => {
      // console.log(res.response)
      messageApi.open({
        type: 'error',
        content: res.response.data.message,
      });
    })
  };

  // 登录失败
  const onFinishFailed = (errorInfo: any) => {
    console.log('失败:', errorInfo);
  };

  type FieldType = {
    username?: string,
    password?: string;
    Nickname?: string;
  };

  const [codeTime, setCodeTime] = useState(10)
  const [sendSwitch, setSendSwitch] = useState(true)
  const [html, setHtml] = useState([])

  // 发送验证码
  const sendCode = async () => {
    if (sendSwitch) {
      setSendSwitch(!sendSwitch)
      let time = 10
      let timer = setInterval(() => {
        time--;
        setCodeTime(time)
        if (time <= 0) {
          // 清空定时器
          clearInterval(timer)
          setCodeTime(10)
          setSendSwitch(true)
        }
      }, 1000)
      await axios.get('/user/captcha').then((res: any) => {
        console.log(res)
        setHtml(res.data)
      })
    }
  }


  return (
    <div className='bgLogin'>
      <div className='loginForm'>
        {contextHolder}
        <h2>宏烨找房后台系统</h2><br />
        <Form
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item<FieldType>
            label="用户名"
            name="username"
            rules={[
              {
                required: true,
                message: '账号不能为空',
              }
            ]}

          >
            <Input placeholder='请输入账号' />
          </Form.Item>

          <Form.Item<FieldType>
            label="密码"
            name="password"
            rules={[
              {
                required: true,
                message: '密码不能为空',
              }
            ]}
          >
            <Input.Password placeholder='请输入密码' />
          </Form.Item>

          <div style={{ display: 'flex', float: 'right' }}>
            <Form.Item<FieldType>
              style={{ marginRight: '45px' }}
              label="验证码"
              name="Nickname"
              rules={[
                {
                  required: true,
                  message: '验证码不能为空'
                }
              ]}
            >
              <Input placeholder='请输入验证码' style={{ width: '15rem' }} />
            </Form.Item>
            <Button type='primary'
              style={sendSwitch ? { color: '#fff' } : { background: '#ccc' }}
              onClick={sendCode}
            >{sendSwitch ? '生成验证码' : `${codeTime}秒后重新发送`}
            </Button>
          </div><br />

          <div style={{ display: 'flex', alignItems: 'cenetr', justifyContent: 'center' }}>
            {/* 生成随机验证码 */}
            <div style={{ width: '150px', height: '60px', marginLeft: '400px' }} dangerouslySetInnerHTML={{ __html: html }}></div>
          </div>

          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button type="primary" htmlType="submit">
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>


  )
}

export default Index